package app.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import app.widget.PASafeKeyBoard.KeyBoardView;
import app.widget.PASafeKeyBoard.KeyBoardView.OnKeyDownBtnListener;
import app.widget.PASafeKeyBoard.KeyBoardView.OnKeyExitBtnListener;
import app.widget.PASafeKeyBoard.KeyBoardView.OnKeySureBtnListener;

import com.longevityassistant.activity.R;

public class PAAccNoEditText extends EditText implements OnFocusChangeListener ,OnClickListener {

	// 控制光标闪烁的计数器
	private int count;
	// 彩色背景的画笔
	private Paint rectPaint;
	// 字体的画笔
	private Paint textPaint;
	// 文字的高，宽及空格的宽
	private float textHeigth;
	private float textWidth;
	private float spaceWidth;
	// 第一次彩色背景的开始位置
	float firstDX;
	// 第二次彩色背景的开始位置
	float secondDX;
	// 第三次彩色背景的开始位置
	float thirdDX;
	// 第四次彩色背景的开始位置
	float fouthDX;
	
	/**
	 * 上下文
	 */
	private Context context;
	/**
	 * 得到window中某个控件的位置数组
	 */
	private int editLocations[] = new int[2];
	/**
	 * 屏幕的高度
	 */
	private int screenHeight;
	/**
	 * 是否移动过
	 */
	private boolean isMove = false;
	/**
	 * 输入法Manager
	 */
	private InputMethodManager imm;
	
	private KeyBoardView keyBoardView;
	private static final int KEYBOARD = -1;
	
	private Handler handler = new Handler();

	public PAAccNoEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	public PAAccNoEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public PAAccNoEditText(Context context) {
		super(context);
		init(context);
	}

	private void init(Context context) {
		this.setInputType(InputType.TYPE_NULL);
		imm = (InputMethodManager) getContext().getSystemService(
				Context.INPUT_METHOD_SERVICE);
		WindowManager windowManager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		screenHeight = windowManager.getDefaultDisplay().getHeight();
		

		setOnFocusChangeListener(this);
		setOnClickListener(this);
		
		LayoutInflater inflater = LayoutInflater.from(context);
		View inflateView = inflater.inflate(R.layout.app_widget_keyboard, null);
		keyBoardView = new KeyBoardView(inflateView,
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
				KEYBOARD, context);
		keyBoardView.setOnKeyDownBtnListener(new OnKeyDownBtnListener() {
			@Override
			public void onKeyDownBtn(KeyEvent event) {
				//PABankLog.i("zbkc", "onKeyDownBtn:" + event);
				dispatchKeyEvent(event);
			}
		});

		keyBoardView.setOnKeyExitBtnListener(new OnKeyExitBtnListener() {
			@Override
			public void onKeyExitBtn() {

				hideKeyBoard();
			}
		});

		keyBoardView.setOnKeySureBtnListener(new OnKeySureBtnListener() {
			@Override
			public void onKeySureBtn() {
				hideKeyBoard();
			}
		});

		
		keyBoardView.setAnimationStyle(android.R.style.Animation_InputMethod);

		keyBoardView.setEditText(this);
		
		keyBoardView.getBtnpoint().setEnabled(false);
		
		
		// 彩色背景画笔的初始化
		rectPaint = new Paint();
		rectPaint.setColor(0xffe1a62e);
		// hint字体画笔的初始化
		textPaint = getPaint();
		// 获取文字的高，宽
		textHeigth = (int) getTextSize();
		// textWidth = textHeigth / 2;
		textWidth = textPaint.measureText("2");
		spaceWidth = textPaint.measureText(" ");
		// 设置第一次彩色背景的开始位置
		firstDX = textWidth * 4 + spaceWidth;
		// 设置第二次彩色背景的开始位置
		secondDX = textWidth * 12 + spaceWidth * 3;
		// 设置第三次彩色背景的开始位置
		thirdDX = textWidth * 20 + spaceWidth * 5;
		// 设置第四次彩色背景的开始位置
		fouthDX = textWidth * 28 + spaceWidth * 7;
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

			ViewGroup view = (ViewGroup) getRootView();
			if (keyBoardView.isShowing()) {
				keyBoardView.dismiss();
				if (isMove) {
					resumeLayout(view);
				}
				return true;
			}

		}

		return super.dispatchKeyEvent(event);
	}

	/**
	 * 
	 * [一句话功能简述]<BR>
	 * [功能详细描述] 隐藏键盘
	 */
	public void hideKeyBoard() {
		ViewGroup view = (ViewGroup) this.getRootView();
		if (keyBoardView.isShowing()) {
			keyBoardView.dismiss();
			if (isMove) {
				resumeLayout(view);
			}
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// 开始计数，逢偶数请为零
		count++;
		count = count % 2;
		String hint = "";
		// 获取要画的文字
		String orgText = getText().toString();
		// 获取要画的文字长度
		int textLength = orgText.length();
		try {
			hint = getHint().toString();
		} catch (Exception e) {
			hint = "";
		}
		int hintLength = hint.length();
		// 获取开始画文字的x，y坐标
		int x = 0;
		int y = getBaseline();
		//Log.i("TAG", "(x=" + x + ", y=" + y + ")");
		// 如果用户没输入则为提示文字
		if (textLength == 0 && hintLength != 0) {
			drawHint(hint, x, y, canvas);
		}
		drawText(orgText, x, y, textLength, canvas);
		
	}
	
	private Runnable drawCursorTask = new Runnable() {
		@Override
		public void run() {
			if (isFocusable()) {
				invalidate();
				handler.postDelayed(drawCursorTask, 500);
			}
		}
	};
	

	public void drawText(String text, int startX, int startY, int textLength,
			Canvas canvas) {
		StringBuffer sb = new StringBuffer();
		char[] texts = text.toCharArray();
		int c = 1;
		int spaceCount = 0;
		for (int i = 0; i < texts.length; i++) {
			// 每4个数字后加一个空格
			sb.append(texts[i]);
			if (c == 4) {
				sb.append(" ");
				spaceCount++;
				c = 0;
			}
			c++;

		}

		// 输入字符串的左移
		float charWidth = getPaint().measureText(" ");
		float textShuldWidth = textPaint.measureText(text) + charWidth
				* (spaceCount + 2);
		if (textShuldWidth >= getWidth()) {
			float transX = charWidth * (spaceCount + 3);
			canvas.translate(-transX, 0);
			Log.i("zbkc",
					"transX:" + transX + ", canvas matrix:"
							+ canvas.getMatrix());
		}

		for (int i = 0; i < texts.length; i++) {
			// 第二、第四组、第六组、第八组数字加上彩色背景
			int j = i / 4;
			if (j == 1) {
				canvas.drawRect(startX + firstDX, startY - textHeigth, startX
						+ firstDX + (i - 3) * textWidth + 4, startY + 3,
						rectPaint);
			} else if (j == 3) {
				canvas.drawRect(startX + secondDX, startY - textHeigth, startX
						+ secondDX + (i - 11) * textWidth + 4, startY + 3,
						rectPaint);
			} else if (j == 5) {
				canvas.drawRect(startX + thirdDX, startY - textHeigth, startX
						+ thirdDX + (i - 19) * textWidth + 4, startY + 3,
						rectPaint);
			} else if (j == 7) {
				canvas.drawRect(startX + fouthDX, startY - textHeigth, startX
						+ fouthDX + (i - 27) * textWidth + 4, startY + 3,
						rectPaint);
			}
		}

		String drawText = sb.toString();
		// 光标
		if (!isFocused()) {
			count = 1;
		}
		if (count == 0) {
			drawText = drawText + "|";
		}

		// 画出数字和光标
		textPaint.setColor(Color.BLACK);
		canvas.drawText(drawText, startX + textWidth / 2 - 4, startY, textPaint);
		// 设置光标的位置为最后，用户不可改变输入位置
		this.setSelection(textLength);
	}

	public void drawHint(String hint, int startX, int startY, Canvas canvas) {
		// 画出提示
		textPaint.setColor(Color.GRAY);
		canvas.drawText(hint, startX + textWidth / 2, startY, textPaint);
		// 设置光标的位置为最后，用户不可改变输入位置
		this.setSelection(0);
	}

	
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (hasFocus) {
			handler.post(drawCursorTask);
		} else {
			handler.removeCallbacks(drawCursorTask);
		}
		//PABankLog.i("zbkc", "onFocusChange event!!! FOCUSTAG:");
		((EditText) v).setInputType(InputType.TYPE_NULL);
		boolean isHide = imm.hideSoftInputFromWindow(this.getRootView()
				.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			final ViewGroup view = (ViewGroup) this.getRootView();
			Handler handler = new Handler();
			if (hasFocus && this.hasWindowFocus()) {
				// 设置时间解决 该键盘与系统键盘同时存在界面最下方时挤动布局覆盖输入框的bug
				int time = 200;
				if (isHide) {
					time = 600;
				}
				//PABankLog.i("zbkc", "time:" + time);
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						calculateLayout(view, keyBoardView);

					}
				}, time);
				keyBoardView.showAtLocation(view, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT);

				//PABankLog.i("zbkc", "hasFocus && this.hasWindowFocus()");

			} else {
				
				if (keyBoardView.isShowing()) {
					keyBoardView.dismiss();
				}
				if (isMove) {
					resumeLayout(view);
				}
			}
			
		
	}

	/**
	 * 
	 * [一句话功能简述]<BR>
	 * [功能详细描述] 计算layout
	 * 
	 * @param view
	 * @param keyBoardView
	 */
	private void calculateLayout(ViewGroup view, KeyBoardView keyBoardView) {
		int keyBoardHeight = keyBoardView.getContentView().getHeight();
		this.getLocationInWindow(editLocations);
		// Log.i("zbkc", "getLocationInWindow" + editLocations[1]);
		int movePosition = editLocations[1] - (screenHeight - keyBoardHeight)
				+ this.getHeight();
		if (movePosition > 0) {
			// Log.i("zbkc", movePosition + "");
			scrollLayout(view, movePosition);
			isMove = true;
		}
	}

	/**
	 * 
	 * [一句话功能简述]<BR>
	 * [功能详细描述] 恢复layout
	 * 
	 * @param view
	 */
	private void resumeLayout(ViewGroup view) {
		view.getChildAt(0).scrollTo(0, 0);
		view.postInvalidate();
	}

	/**
	 * 
	 * [一句话功能简述]<BR>
	 * [功能详细描述] 滚动layout
	 * 
	 * @param view
	 * @param position
	 */
	private void scrollLayout(ViewGroup view, int position) {
		view.getChildAt(0).scrollTo(0, position);
		view.postInvalidate();
	}

	@Override
	public void onClick(View v) {
		invalidate();
		((EditText) v).setInputType(InputType.TYPE_NULL);

		imm.hideSoftInputFromWindow(this.getRootView().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
			final ViewGroup view = (ViewGroup) this.getRootView();

			if (!keyBoardView.isShowing()) {
				imm.hideSoftInputFromWindow(
						this.getRootView().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						calculateLayout(view, keyBoardView);
					}
				}, 200);
				keyBoardView.showAtLocation(view, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, LayoutParams.FILL_PARENT,
						LayoutParams.WRAP_CONTENT);
			}
	}
	
	@Override
	protected void onTextChanged(CharSequence text, int start, int before,
			int after) {
		String result = text.toString();
		if (this.getText().toString().length() > 0 && this.isFocused()){
			if (!result.matches("^[0-9]*$")) {
				this.setText(result.subSequence(0, result.length() - 1));
				setSelection(getText().toString().length());
			} 
		}
		super.onTextChanged(text, start, before, after);
	}
}
